package user

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/pkg/constant"
	"go-zero-admin/pkg/ctxdata"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/fx"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetRolesPostsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewGetRolesPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *GetRolesPostsLogic {
	return &GetRolesPostsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *GetRolesPostsLogic) GetRolesPosts(req *types.GetRolesPostsReq) (resp *types.GetRolesPostsResp, err error) {
	// 查询出角色数据
	roleListResp, err := l.svcCtx.RoleRpc.GetRoleList(l.ctx, &syspb.GetRoleListReq{
		Status:          convertor.ToString(constant.RoleStatusOn),
		IsDataScope:     true,
		DataScopeUserId: ctxdata.GetUidFromCtx(l.ctx),
	})
	if err != nil {
		return nil, err
	}
	roleList := roleListResp.GetList()

	// 处理角色数据
	sysRoleList := make([]*types.SysRole, 0)
	if len(roleList) != 0 {
		fx.From(func(source chan<- interface{}) {
			for _, v := range roleList {
				source <- v
			}
		}).Map(func(item interface{}) interface{} {
			var role types.SysRole
			_ = copier.Copy(&role, item.(*syspb.SysRole))

			return &role
		}).ForEach(func(item interface{}) {
			sysRoleList = append(sysRoleList, item.(*types.SysRole))
		})
	}

	// 查询出岗位数据
	postListResp, err := l.svcCtx.PostRpc.GetPostList(l.ctx, &syspb.GetPostListReq{
		Status: convertor.ToString(constant.PostStatusOn),
	})
	if err != nil {
		return nil, err
	}
	postList := postListResp.GetList()

	// 处理岗位数据
	sysPostList := make([]*types.SysPost, 0)
	if len(postList) != 0 {
		fx.From(func(source chan<- interface{}) {
			for _, v := range postList {
				source <- v
			}
		}).Map(func(item interface{}) interface{} {
			var post types.SysPost
			_ = copier.Copy(&post, item.(*syspb.SysPost))

			return &post
		}).ForEach(func(item interface{}) {
			sysPostList = append(sysPostList, item.(*types.SysPost))
		})
	}

	return &types.GetRolesPostsResp{
		RoleList: sysRoleList,
		PostList: sysPostList,
	}, nil
}
